package com.example.questionsystem.modules.qu.service.impl;

import cn.hutool.core.util.URLUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


import java.io.IOException;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.*;

public class HtmlProcessor {



    /**
     * 处理HTML中的图片标签
     * @param html 原始HTML内容
     * @param imageDir 图片存储目录
     * @return 处理后的HTML和图片映射关系
     */
    public static ProcessResult processHtmlImages(String html, Path imageDir) throws IOException {
        Document doc = Jsoup.parse(html);
        Elements imgs = doc.select("img[src]");
        Map<String, String> imageMapping = new HashMap<>();

        for (Element img : imgs) {
            String originalUrl = img.attr("src");
            
            // 生成唯一文件名
            String newFileName = generateFileName(originalUrl);
            Path targetPath = imageDir.resolve(newFileName);
            
            // 下载并保存图片
            ImageDownloader.downloadImage(originalUrl, targetPath);

            // 记录映射关系
            imageMapping.put(originalUrl, "files/" + newFileName);

            // 替换src属性
            img.attr("src", "files/" + newFileName);
        }

        return new ProcessResult(
            doc.body().children().outerHtml(), 
            imageMapping,
            null
        );
    }
    /**
     * 处理HTML中的图片标签
     * @param html 原始HTML内容
     * @param imageDir 图片存储目录
     * @return 处理后的HTML和图片映射关系
     */
    public static ProcessResult processHtmlBaseImages(String html, Path imageDir,String key) throws Exception {
        Document doc = Jsoup.parse(html);
        Elements imgs = doc.select("img[src]");
        Map<String, String> imageMapping = new HashMap<>();
        // 初始化 downloadResultMap
        Map<String, ImageDownloader.DownloadResult> downloadResultMap = new HashMap<>();
        for (Element img : imgs) {
            String originalUrl = img.attr("src");

            // 生成唯一文件名
            String newFileName = generateFileName(originalUrl);
            Path targetPath = imageDir.resolve(newFileName);

            // 下载并保存图片
            ImageDownloader.DownloadResult downloadResult = ImageDownloader.downloadEncryptImage(originalUrl, targetPath, key);
            downloadResult.setEncryptedFilePath("files/" + newFileName);
            downloadResultMap.put(newFileName, downloadResult);

            // 记录映射关系
            imageMapping.put(originalUrl, "files/" + newFileName);

            // 替换src属性
            img.attr("src", "files/" + newFileName);
        }

        return new ProcessResult(
                doc.body().children().outerHtml(),
                imageMapping,
                downloadResultMap
        );
    }
    /**
     * 处理HTML中的图片标签
     * @param html 原始HTML内容
     * @param imageDir 图片存储目录
     * @return 处理后的HTML和图片映射关系
     */
    public static ProcessResult  processHtmlEncryptorImages(String html, Path imageDir,String key) throws Exception {
        Document doc = Jsoup.parse(html);
        Elements imgs = doc.select("img[src]");
        Map<String, String> imageMapping = new HashMap<>();

        for (Element img : imgs) {
            String originalUrl = img.attr("src");

            // 生成唯一文件名
            String newFileName = generateFileName(originalUrl);
            Path targetPath = imageDir.resolve(newFileName);

            // 下载并保存图片
          //  ImageDownloader.downloadAndEncrypt(originalUrl, String.valueOf(targetPath),key);

            // 记录映射关系
            imageMapping.put(originalUrl, "files/" + newFileName);

            // 替换src属性
            img.attr("src", "files/" + newFileName);
        }

        return new ProcessResult(
                doc.body().children().outerHtml(),
                imageMapping,
                null
        );
    }
    private static String generateFileName(String url) {
        String ext = getFileExtension(url);

        // 获取当前时间戳
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        return UUID.randomUUID().toString().substring(0, 8) + "_" + timestamp + ext;
    }

    private static String getFileExtension(String url) {
        String path = URLUtil.getPath(url);
        int dotIndex = path.lastIndexOf('.');
        return (dotIndex > 0) ? path.substring(dotIndex) : ".jpg";
    }

    @Data
    @AllArgsConstructor
    public static class ProcessResult {
        private String processedHtml;
        private Map<String, String> imageMapping;
        private Map<String, ImageDownloader.DownloadResult> imageDownloadResult;
    }
}